package cn.tjad.tjad2.module.document.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.hjy.http.cache.DownloadCacheHelper;
import com.hjy.http.cache.db.DBSql;
import com.hjy.http.download.DownloadManager;
import com.hjy.http.download.FileDownloadInfo;
import com.hjy.http.download.FileDownloadTask;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.tjad.tjad2.module.common.fragment.BaseTransferFragment;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.module.document.adapter.DownLoadListAdapter;
import cn.tjad.tjad2.utils.FileOpenUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

public class DownloadTransferFragment extends BaseTransferFragment implements OnItemClickListener {

    private DownLoadListAdapter adapter;
    private final List<FileDownloadTask> downloadTaskList = new ArrayList<>();

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        List<Map<String, String>> cacheData = DownloadCacheHelper.getInstance().getAllRecords();
        List<FileDownloadTask> cache = convert(cacheData);
        if (cacheData != null) {
            downloadTaskList.addAll(cache);
        }
        adapter = new DownLoadListAdapter(downloadTaskList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
    }

    private List<FileDownloadTask> convert(List<Map<String, String>> origin) {
        if (origin == null) {
            return null;
        }
        List<FileDownloadTask> dest = new ArrayList<>();
        if (origin.size() > 0) {
            for (Map<String, String> element : origin) {
                String url = element.get(DBSql.COL_DLHIS_URL);
                String localPath = element.get(DBSql.COL_DLHIS_LOCAL_PATH);
                if (localPath != null) {
                    if (localPath.endsWith("view.js") || localPath.endsWith("view.html")) {
                        continue;
                    }
                }
                String status = element.get(DBSql.COL_DLHIS_STATUS);
                String time = element.get(DBSql.COL_DLHIS_TIME);
                String fileSize = element.get(DBSql.COL_DLHIS_FILE_SIZE);
                String downloadSize = element.get(DBSql.COL_DLHIS_FILE_DOWNLOAD_SIZE);
                String fileVersion = element.get(DBSql.COL_DLHIS_FILE_VERSION);
                FileDownloadInfo info = new FileDownloadInfo(url, url, new File(localPath), null, null);
                FileDownloadTask task = new FileDownloadTask(info, null, null);
                task.setDownloadStatus(Integer.parseInt(status));
                task.setStartTime(Long.parseLong(time));
                task.setCurrSize(Long.parseLong(downloadSize));
                task.setTotalSize(Long.parseLong(fileSize));
                dest.add(task);
            }
        }
        return dest;
    }

    @Override
    public void onItemClick(View parentView, View itemView, final int position) {
        final FileDownloadTask task = adapter.getItemData(position);
        FileDownloadInfo info = task.getFileDownloadInfo();
        File file = info.getOutFile();
        if (task.getDownloadStatus() == FileDownloadTask.STATUS_DOWNLOAD_SUCCESS) {
            if (file != null && file.exists()) {
                FileOpenUtils.openFile(file, (Activity) itemView.getContext());
            } else {
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                builder.setTitle("提示")
                        .setMessage("文件不存在, 可能已被删除, 是否重新下载?")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("重新下载", new OnDialogClickListener() {
                            @Override
                            public boolean onClick(Dialog dialogInterface, int i) {
                                DownloadManager.getInstance().executeTask(task, true);
                                return true;
                            }
                        })
                        .setNeutralButton("删除记录", new OnDialogClickListener() {
                            @Override
                            public boolean onClick(Dialog dialogInterface, int i) {
                                downloadTaskList.remove(position);
                                adapter.notifyDataSetChanged();
                                return true;
                            }
                        })
                        .show(getChildFragmentManager());
            }
        } else if (task.getDownloadStatus() == FileDownloadTask.STATUS_DOWNLOADING) {
            Tools.showToast("文件正在下载中, 请等下载完成后再试");
        } else if (task.getDownloadStatus() == FileDownloadTask.STATUS_DOWNLOAD_FAILED){
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
            builder.setTitle("提示")
                    .setMessage("文件未下载完成, 是否继续下载?")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("继续下载", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
                            DownloadManager.getInstance().executeTask(task, false);
                            return true;
                        }
                    })
                    .setNeutralButton("重新下载", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
                            DownloadManager.getInstance().executeTask(task, true);
                            return true;
                        }
                    })
                    .show(getChildFragmentManager());
        }
    }
}
